package com.liuwei.spring.cloud.framework.feigns.provider;
/**
 * Description :
 *
 * @Author Evan Liu
 * @Date 2019年4月24日
 */
/*
 * Copyright 2012-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.ArrayUtil;
import com.liuwei.spring.cloud.common.utils.StringPool;
import com.liuwei.spring.cloud.framework.spring.ApplicationHelper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import java.io.IOException;

/**
 * 拦截所有的 /api/feign/* 请求进行鉴权
 * @author liuwei
 */
@Slf4j
public class FeignLogFilter extends OncePerRequestFilter implements Ordered {
    /** Not LOWEST_PRECEDENCE, but near the end, so it has a good chance of catching all enriched headers, but users can add stuff after this if they want to */
    private int order = Ordered.LOWEST_PRECEDENCE - 10;

    @Override
    public int getOrder() {
        return this.order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    /**
     * request 的inputStream和response 的outputStream默认情况下是只能读一次， 不可重复读
     * https://www.jianshu.com/p/afdd31bfbf94
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            // 调用方信息
            String uri = request.getRequestURI().toString();
            String callerCluster = request.getHeader(StringPool.Feign_Caller_Cluster);
            String callerApplication = request.getHeader(StringPool.Feign_Caller_Application);
            String callerIp = getClientIP(request);

            // 提供方信息
            String calleeCluster = ApplicationHelper.getApplicationCluster();
            String calleeApplication = ApplicationHelper.getApplicationName();
            String calleeIp = NetUtil.getLocalhostStr();

            String feignInvoker = request.getHeader(StringPool.Feign_Invoker);
            if(StringUtils.equalsIgnoreCase(feignInvoker,StringPool.ONE)){
                log.info("FeignRequest:[{}] Caller:[{}][{}][{}] Provider:[{}][{}][{}]", uri, callerCluster, callerApplication, callerIp, calleeCluster, calleeApplication, calleeIp);
            }else{
                log.info("HttpRequest:[{}] Caller:[{}][{}][{}] Provider:[{}][{}][{}]", uri, callerCluster, callerApplication, callerIp, calleeCluster, calleeApplication, calleeIp);
            }
        } catch (Exception e) {
            log.info("Error:{}",e.getMessage(),e);
        }
        filterChain.doFilter(request, response);
    }

    public static String getClientIP(HttpServletRequest request, String... otherHeaderNames) {
        String[] headers = new String[]{"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
        if (ArrayUtil.isNotEmpty(otherHeaderNames)) {
            headers = (String[])ArrayUtil.addAll(new String[][]{headers, otherHeaderNames});
        }
        return getClientIPByHeader(request, headers);
    }

    public static String getClientIPByHeader(HttpServletRequest request, String... headerNames) {
        String[] var3 = headerNames;
        int var4 = headerNames.length;
        String ip;
        for(int var5 = 0; var5 < var4; ++var5) {
            String header = var3[var5];
            ip = request.getHeader(header);
            if (!NetUtil.isUnknown(ip)) {
                return NetUtil.getMultistageReverseProxyIp(ip);
            }
        }
        ip = request.getRemoteAddr();
        return NetUtil.getMultistageReverseProxyIp(ip);
    }
}


